define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
     var operas=0;
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'point/flow/index',
                    add_url: 'point/flow/add',
                    // edit_url: 'point/flow/edit',
                    // del_url: 'point/flow/del',
                    multi_url: 'point/flow/multi',
                    table: 'region_config',
                }
            });
            require(['jstree'], function () {                
                //全选和展开
                $(document).on("click", "#checkall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
                });
                $(document).on("click", "#expandall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "open_all" : "close_all");
                });                
                $(".content").click();
                $('#channeltree').bind("changed.jstree", function (e, data) {                    
                    var treeNode = $('#channeltree').jstree(true).get_selected(true)[0]; //获取所有选中的节点对象
                    if(!treeNode){ 
                        operas='0';                       
                        return false;
                    }
                    if(operas==treeNode.id){
                       return false;
                    }
                    operas=treeNode.id;
                    var treeNodeParents = treeNode.parents.slice(0,-1);
                    treeNodeParents.push(treeNode.original.id);
                    var getlevel = Controller.getlevel(treeNodeParents.join(","));
                    $(".titles").html(getlevel.tag_name+'详情');
                    $('#ids').html(getlevel.is_sign);
                    $('#name').html(getlevel.tag_name);
                    $('#tag_id').html(getlevel.tag_id);
                                        
                    $("#table").bootstrapTable('destroy', {});
                    $("#table").bootstrapTable('refresh', {});
                    setTimeout(function () {
                       Controller.flowtable();  
                    }, 700);                 
                        
                    return false;
                });
                    
            
            $('#channeltree').jstree({
                    "themes": {
                        "stripes": true,
                    },
                    "checkbox": {
                        "keep_selected_style": false,
                        "three_state": false, //如果想选择父节点时不全选子节点，就需要加上下面这句
                    },
                    "types": {
                        "channel": {
                            "icon": "fa fa-file-o",
                        },
                        "list": {
                            "icon": "fa fa-folder-o",  //非任务图标
                        },
                        "link": {
                            "icon": "fa fa-link",
                        },
                        "disabled": {
                            "check_node": false,
                            "uncheck_node": false
                        }
                    },
                    // "state"
                    'plugins': ["types", "checkbox","contextmenu"],
                    // "contextmenu":{
                    //     "items" : customMenu,
                    //     "select_node":false,//取消右击选中事件
                    // },                    
                    "core": {
                        // "multiple": true,
                        "multiple": false,//单选
                        'check_callback': true,
                        "data": tagList
                    }
                });
            });
           //  刷新树
            $(document).on('click',".btn-tree",function(){
                //  获取当前页面的utl
                var url =  window.location.href;
                location.reload(url);                 
            })
            $(document).on("click", ".update-success", function () {
                $.ajax({
                    url: 'flow/update_flow',
                    type: 'post',
                    data: {},
                    dataType: 'json',
                    beforeSend: function () {
                        i = layer.msg('更新中请稍等...', {icon: 16,shade: [0.5, '#393D49'],scrollbar: false,offset:'50%',time:60*1000});
                    },
                    success:function(json){
                        layer.close(i);
                        layer.alert(json.msg);
                        $(".btn-refresh").click();
                    }
                });
            });
        },
        // 标记树结构等级
        getlevel:function(ids){            
            var datajson = "";
            $.ajax({
                type:"POST",
                url: "point/flow/gettopid",
                data:{ids:ids},
                dataType:"json",
                async: false,
                success:function(data){
                    datajson = data;
                }
            });
            return datajson;
        }, 
        // 流量结算列表               
        flowtable:function(url){
            var table = $("#table");
            var tag_id = $("#tag_id").html();
            table.bootstrapTable('refresh');
            table.bootstrapTable('destroy');
            // 初始化表格
            table.bootstrapTable({
                url: 'point/flow/flow_table?tag_id='+tag_id+'&divided='+divided,
                pk: 'ops_topflow_month.id',
                sortName: 'ops_topflow_month.id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'ops_topflow_month.id', title: __('ID'),formatter: function (data, full) {
                                return full.id;
                            }},
                        {
                            field: 'monthly',
                            title: __('Monthly'),
                            operate: 'BETWEEN',
                            addclass: 'datetimepicker',
                            data: 'data-date-format="YYYY-MM"'
                        },
                        {field: 'tag2.name', title: __('出口名称'), placeholder: __('模糊查询'), operate: 'LIKE %...%',
                            formatter: function (data, full) {
                                return full.export_name;
                            }},
                        
                        {
                            field: 'ops_topflow_month.servicesoutflow',
                            title: __('Servicesoutflow')+units,
                            placeholder: __('数字'),
                            operate: 'BETWEEN',
                            formatter: function (data, full) {
                                if (full.servicesoutflow==null||full.servicesoutflow=='') {
                                    return '-';
                                } else {
                                    return (full.servicesoutflow /divided).toFixed(2);
                                }
                            }
                        },
                        {
                            field: 'ops_topflow_month.band',
                            title: __('band'),
                            placeholder: __('数字'),
                            operate: 'BETWEEN',
                            formatter: function (data, full) {
                                if (full.band==null || full.band=='') {
                                    return '-';
                                } else {
                                    return full.band;
                                }
                            }
                        },
                        {
                            field: 'ops_topflow_month.payment',
                            title: __('Payment'),
                            searchList:paymentList,
                            formatter: Table.api.formatter.normal,
                            formatter: function (data, full) {
                                return paymentList[full.payment];
                            }
                            
                        },
                        {field: 'ops_topflow_month.comment',title: __('备注'),placeholder: __('模糊查询'),operate: 'LIKE %...%',formatter:function(value,row,index){
                            //var valuerep=value.replace(/\s*/g,"");
                            if(row.comment){
                                    return '<div style="min-width:50px;">' + row.comment + '</div><input type="text" class="form-control text-center" data-field="' + this.field + '" style="width:100%;display:none;min-width:50px;" value="' + value + '">';
                                
                                 }else{
                                    return '<div style="min-width:50px;">' + '<span>&nbsp;</span>'+ '</div><input type="text" class="form-control text-center" data-field="' + this.field + '" style="width:100%;display:none;min-width:50px;" value="">';
                           
                                 }
                            }, events: {

                                'click div': function (e, value, row, index) {
                                    $(this).hide();
                                    $(this).next().show().focus();
                                },
                                'keyup input': function (e, value, row, index) {
                                    if (e.keyCode == 13 || e.keyCode == 10) {
                                        $(this).trigger("blur");
                                    }
                                },
                                'blur input': function (e, value, row, index) {
                                    
                                    var that = this;
                                    var values = $(this).val();
                                    var values1=$(this).prev().text();
                                    if(values1.replace(/\s*/g,"")=="" && values.replace(/\s*/g,"") == ""){
                                        $(that).prev().html('<span>&nbsp;</span>').show();
                                        $(that).attr("value","");
                                        $(that).hide();
                                        $(that).prev().show();
                                        return false;
                                    }
                                    if (values1 != values) {
                                        var data = {};
                                        data["row[" + $(that).data("field") + "]"] = values;
                                        Fast.api.ajax({
                                            url:  "point/flow/editflowcomment?ids=" + row.id+"&comment="+values,
                                            data: data
                                        }, function (data, ret) {
                                            $(that).hide();
                                            if(values.replace(/\s*/g,"") == ""){
                                                $(that).prev().html('<span>&nbsp;</span>').show();
                                                $(that).attr("value","");
                                                $(this).val("");
                                            }else{
                                                $(that).prev().text(values).show();
                                                $(that).attr("value",values);
                                                $(this).val(values);
                                            }
                                            
                                        });
                                    } else {
                                        $(that).hide();
                                        $(that).prev().show();
                                    }
                                }
                        }},
                        {field: 'ops_topflow_month.updatetime', title: __('更新时间'), operate:'RANGE', addclass:'datetimerange',formatter: Table.api.formatter.datetime, 
                            formatter: function (data, full) {
                                return full.updatetime;
                            }},

                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    // name: 'detail',
                                    // text: '绑定',
                                    // title: '绑定标签',
                                    // classname: 'btn btn-xs btn-success btn-dialog',
                                    // icon: 'fa fa-plus',

                                    name: 'detail',
                                    text: '原始数据',
                                    title: '原始数据',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-folder-o',
                                    url: '/admin/point/flow/addtabs',
                                    visible: function (row, full) {
                                        if(row.payment == 4){
                                            return false;
                                        }else{
                                            full.url = "/admin/point/flow/addtabs/ids/"+row.id+"?monthly="+row.monthly;
                                            return true;    
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });


            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        addtabs: function () {
            // 初始化表格参数配置
            Table.api.init();
            Controller.table['second'].call(this);
        },

        table: {
            second: function () {
                //获取ID
                var a = $("#ids").html();

                // 表格2
                var table2 = $("#table2");
                table2.bootstrapTable({
                    url: 'point/flow/basic_data?ids=' + a+'&divided='+divided,
                    toolbar: '#toolbar2',
                    // sortName: 'IfIndex',
                    // search: false,
                    // searchFormVisible: false,
                    // commonSearch: false,
                    // showExport: false,
                    // showToggle: false,
                    // showColumns: false,
                    pageSize: 10,
                    columns: [
                        [
                            {field: 'id', title: __('ID')},
                            // {field: 'device_id', title:__('设备ID')},

                            {
                                field: 'values',
                                title: __('Servicesoutflow')+units,
                                placeholder: __('数字'),
                                operate: 'BETWEEN',
                                formatter: function (data, full) {
                                    if (data == 0) {
                                        return '-';
                                    } else {
                                        return (data/divided).toFixed(2);
                                    }
                                }
                            },
                            {
                                field: 'everyDay', title: __('Everyday'), operate: 'BETWEEN',
                                addclass: 'datetimepicker',
                                data: 'data-date-format="YYYY-MM-DD"'
                            },


                        ]
                    ]
                });


                // 为表格2绑定事件
                Table.api.bindevent(table2);

                /*table2Obj=setInterval(function(){
                 $('.btn-refresh').click();
                 },10000);*/
            },
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
            $('select[name="row[tag_id]"]').attr("disabled", "disabled");
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});